<!-- eslint-disable vue/valid-v-model -->
<template>
  <div class="common-layout">
    <HeadContent title="员工信息管理"></HeadContent>
    <TagComtent></TagComtent>
    <el-container>
      <el-main>
        <el-space wrap :size="size">
          <div class="flex flex-wrap gap-4">
            <el-card style="width: 150vh" shadow="hover">
              <el-form :model="form" :inline="true" class="demo-form-inline">
                <el-form-item label="姓名">
                  <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-select v-model="form.sex" placeholder="---请选择---">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位">
                  <el-select v-model="form.posi" placeholder="---请选择---">
                    <el-option v-for="item in PosList" :key="item.posId" :label="item.posName" :value="item.posId" />
                  </el-select>
                </el-form-item>
                <el-form-item label="部门">
                  <el-select v-model="form.dept" placeholder="---请选择---">
                    <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName"
                      :value="item.deptId" />
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="入职日期">
                  <el-col :span="11">
                    <el-date-picker v-model="form.date1" type="date" placeholder="Pick a date" style="width: 100%" />
                  </el-col>
                </el-form-item> -->
                <el-form-item class="xrequired" label="入职日期:" prop="entryjob">
                  <div class="block">
                    <span class="demonstration"></span>
                    <el-date-picker v-model="form.date1" type="date" placeholder="---请选择---" />
                  </div>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="form.status" placeholder="---请选择---">
                    <el-option label="在职" value="在职" />
                    <el-option label="离职" value="离职" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit"><el-icon>
                      <Search />
                    </el-icon>&nbsp;查询</el-button>
                  <el-button type="primary" @click="resetForm"><el-icon>
                      <RefreshRight />
                    </el-icon>&nbsp;重置</el-button>
                  <el-button type="primary" @click="router.push('/addstaff')"><el-icon>
                      <CirclePlus />
                    </el-icon>&nbsp;新增员工</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <el-card style="width: 150vh" shadow="hover">
            <el-table :data="staffInfo" style="width: 100%">
              <el-table-column fixed prop="empId" label="员工编号" width="120" />
              <el-table-column prop="username" label="姓名" width="120" />
              <el-table-column prop="sex" label="性别" width="120" />
              <el-table-column prop="posName" label="职位" width="120" />
              <el-table-column prop="deptName" label="部门" width="120" />
              <el-table-column prop="status" label="状态" width="100" />
              <el-table-column fixed="right" label="操作" min-width="200">
                <template #default="scope">
                  <el-button type="primary" size="100px"
                    @click="router.push({ path: '/staffinfo', query: { id: scope.row.empId } })">
                    <el-icon>
                      <View />
                    </el-icon>&nbsp;查看
                  </el-button>
                  <el-button plain @click="doDialogFormVisible(scope.row)" type="warning"><el-icon>
                      <Refresh />
                    </el-icon>&nbsp;修改
                  </el-button>
                  <!-- <div v-if="scope.row.status === '离职'" class="CaozuoDiv">
                    <el-button type="primary" @click="flag = false"><el-icon>
                        <Plus />
                      </el-icon>&nbsp;入职
                    </el-button>
                    <el-button type="success" disabled><el-icon>
                        <Position />
                      </el-icon>&nbsp;跳转
                    </el-button>
                  </div> -->

                  
                    <!-- <el-button type="danger" @click="flag = true"><el-icon>
                        <Minus />
                      </el-icon>&nbsp;离职</el-button> -->
                    <div v-if="scope.row.isReverted" class="CaozuoDiv">
                      <el-button type="primary" @click="revertRow(scope.row)"><el-icon>
                          <Minus />
                        </el-icon>&nbsp;入职</el-button>
                    </div>
                    <div v-else class="CaozuoDiv">
                      <el-button type="danger" @click="revokeRow(scope.row)"><el-icon>
                          <Minus />
                        </el-icon>&nbsp;离职</el-button>
                    </div>
                    <el-button type="success" @click="router.push({ path: '/tiaozhuan', query: { empId: scope.row.empId,username:scope.row.username,deptName:scope.row.deptName,posName:scope.row.posName } })"><el-icon>
                        <Position />
                      </el-icon>&nbsp;跳转</el-button>
                  

                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 分页 -->
          <el-pagination background layout="prev, pager, next" :total="10" />
        </el-space>
      </el-main>
    </el-container>
  </div>
  <!--弹出框内容-->
  <el-dialog v-model="dialogFormVisible" title="修改员工" width="500">
    <el-form :model="updateform">
      <el-form-item label="员工姓名" :label-width="formLabelWidth">
        <el-input v-model="updateform.username" />
      </el-form-item>
      <el-form-item label="登录名" :label-width="formLabelWidth">
        <el-input v-model="updateform.loginName" />
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth">
        <el-select v-model="updateform.sex" placeholder="Please select sex">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="生日" :label-width="formLabelWidth">
        <el-input v-model="updateform.birthStr" />
      </el-form-item>
      <el-form-item label="入职日期" :label-width="formLabelWidth">
        <el-input v-model="updateform.firstJobTimeStr" />
      </el-form-item>

      <el-form-item label="系统权限" :label-width="formLabelWidth">
        <el-select v-model="updateform.authority" placeholder="Please select authority">
          <el-option v-for="authority in authorities" :key="authority.authorityId" :label="authority.name"
            :value="authority.authorityId" />

        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">返回</el-button>
        <el-button type="primary" @click="handleUpdateStaff()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive } from 'vue'



const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

import {
  View, Refresh,  Minus, RefreshRight, CirclePlus,
  Position, Search
} from '@element-plus/icons-vue'
import TagComtent from '@/components/TagComtent.vue'
import HeadContent from '@/components/HeadContent.vue'

// do not use same name with ref
const form = ref({
  name: '',
  sex: '',
  posi: '',
  dept: '',
  date1: '',
  status: '',
})

//查询重置功能 绑定+按钮

const PosList = ref<Pos[]>([])
const getPositionFn = async () => {
  const res = await getPosition()
  PosList.value = res.data
}
getPositionFn()


const deptList = ref<DeptList[]>([])
const getDeptListInfoFn = async () => {
  const res = await getDeptListInfo()
  deptList.value = res.data
}
getDeptListInfoFn()

// const selectStaff1 = ref<selectStaffInfo[]>([])
const newForm = ref<selectStaffInfo>({
  username: '',
  sex: '',
  posId: '',
  deptId: '',
  entryTime: '',
  status: ''

})
//点击查询员工
const onSubmit = async () => {
  const date = new Date(form.value.date1)
  // 提取年月日部分
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1，并使用padStart填充前导零
  const day = date.getDate().toString().padStart(2, '0'); // 使用padStart填充前导零

  // 组合成年月日格式
  const formattedDate = `${year}-${month}-${day}`;

  newForm.value.username = form.value.name
  newForm.value.sex = form.value.sex
  newForm.value.posId = form.value.posi
  newForm.value.deptId = form.value.dept
  newForm.value.entryTime = formattedDate;
  newForm.value.status = form.value.status
  console.log(newForm.value.entryTime);
  resetForm()

  const res = await selectStaff(newForm.value)
  staffInfo.value = res.data;
  for (let i = 0; i < staffInfo.value.length; i++) {
    if (staffInfo.value[i].status == "在职") {
      staffInfo.value[i].isReverted = false;
    }
    else {
      staffInfo.value[i].isReverted = true;
    }
  }
  // for (let i = 0; i < staffInfo.value.length; i++) {
  //   if (staffInfo.value[i].status == "活动") {
  //     staffInfo.value[i].isReverted = false;
  //   }
  //   else {
  //     staffInfo.value[i].isReverted = true;
  //   }
  // }
  console.log(staffInfo.value)
}
function resetForm() {
  form.value = {
    name: '',
    sex: '',
    posi: '',
    dept: '',
    date1: '',
    status: ''
  }
}

// 获取员工的信息接口数据类型
import type { Authority, DeptList, Pos, selectStaffInfo, StaffInfo } from '@/model'
import { getAuthority, getAuthorityById, getStaff, selectStaff, updateEmpStatus, updateStaff, } from '@/api/staff'

const staffInfo = ref<StaffInfo[]>([])
const getStaffFn = async () => {
  const res = await getStaff();
  staffInfo.value = res.data;
  for (let i = 0; i < staffInfo.value.length; i++) {
    if (staffInfo.value[i].status == "在职") {
      staffInfo.value[i].isReverted = false;
    }
    else {
      staffInfo.value[i].isReverted = true;
    }
  }
  console.log(res.data);
}
getStaffFn();

// 修改员工信息
const updateform = reactive({
  empId: 1,
  username: '',
  sex: '',
  birthStr: '',
  firstJobTimeStr: '',
  loginName: '',
  authority: 1
})

const authorities = ref<Authority[]>([])

const getAuthorityFn = async () => {
  const res = await getAuthority()
  authorities.value = res.data
}

getAuthorityFn()
const getAuthorityByIdFn=async(id:number)=>{
  const res = await getAuthorityById(id)
  updateform.authority =parseInt(res.data.authorityId, 10)
  console.log(res)

}
function doDialogFormVisible(row: any) {
  updateform.empId = row.empId
  updateform.username = row.username
  updateform.sex = row.sex
  updateform.birthStr = row.birth
  updateform.firstJobTimeStr = row.firstJobTime
  updateform.loginName = row.loginName
  
getAuthorityByIdFn(row.empId)

  dialogFormVisible.value = true

}
const handleUpdateStaff = async () => {
  if (typeof updateform.authority !== 'number') {
    console.error('authority must be a number');
    return;
  }try {
    await updateStaff(updateform);
    dialogFormVisible.value = false; // 关闭弹窗
    getStaffFn(); // 刷新数据
    ElMessage.success('员工信息更新成功'); //
  }catch (error) {
    console.error('Error updating staff:', error);
    ElMessage.error('员工信息更新失败');
  }
}

async function revertRow(row: any) {
  row.isReverted = false; // 恢复行状态
  // 可能还有其他恢复逻辑...
  await updateEmpStatus(row.empId, '1'); // 调用更新接口，将状态改为活动
  getStaffFn()
  onSubmit()
  
}
async function revokeRow(row: any) {
  row.isReverted = true; // 撤销行状态
  // 可能还有其他撤销逻辑...
  await updateEmpStatus(row.empId, '2');
  getStaffFn()
  onSubmit()
 
}


import { ref } from 'vue'
import router from '@/router'
import { getDeptListInfo } from '@/api/dept'
import { getPosition } from '@/api/pos'

const size = ref(40)
</script>


<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}

.CaozuoDiv {
  margin-left: 12px;
  display: inline
}
</style>
